import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/point_transfer.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/point/point_transfer_history_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PointTransferScreen extends StatefulWidget {
  static const routeName = '/PointTransferScreen';

  @override
  _PointTransferScreenState createState() => _PointTransferScreenState();
}

class _PointTransferScreenState extends State<PointTransferScreen> {
  String _error;
  PointTransferParam _param;
  AccountTypeItem _accountTypeItem;
  String _inUsername;

  TextEditingController _amountController;
  TextEditingController _passwordController;
  TextEditingController _noteController;

  @override
  void initState() {
    super.initState();
    _amountController = TextEditingController();
    _passwordController = TextEditingController();
    _noteController = TextEditingController();
    _fetchPointTransferParam();
  }

  @override
  void dispose() {
    _amountController.dispose();
    _passwordController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("积分转赠"),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pushNamed(
              PointTransferHistoryScreen.routeName,
              arguments: PointTransferQueryReq(
                pageIndex: 0,
                pageSize: 10,
              ),
            ),
            child: Text(
              '转赠历史',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
          ),
        ],
      ),
      body: _error == null && _param == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _param == null
              ? Center(
                  child: Text(_error),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return Padding(
      padding: EdgeInsets.all(8.w),
      child: Column(
        children: [
          ParamsTextWidget(
            text: "请选择积分类型",
          ),
          Container(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: _showAccountType,
              child: Text(_accountTypeItem == null ? "请选择" : _accountTypeItem.name),
            ),
          ),
          SizedBox(
            height: 8.w,
          ),
          ParamsTextWidget(
            text: "请选择受赠账号",
          ),
          Container(
            width: double.infinity,
            child: OutlinedButton(
              onPressed: _showInUsername,
              child: Text(_inUsername == null ? "请选择" : _inUsername),
            ),
          ),
          SizedBox(
            height: 8.w,
          ),
          ParamsTextWidget(
            text: "请输入转赠额度",
          ),
          TextField(
            controller: _amountController,
            decoration: InputDecoration(
              hintText: _accountTypeItem == null ? "" : _accountTypeItem.amountHint,
            ),
            keyboardType: TextInputType.number,
          ),
          SizedBox(
            height: 8.w,
          ),
          if (_accountTypeItem != null && _accountTypeItem.needPassword) ...[
            ParamsTextWidget(
              text: "请输入保护密码",
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(),
              obscureText: true,
            ),
            SizedBox(
              height: 8.w,
            ),
          ],
          ParamsTextWidget(
            text: "请输入备注信息",
            showPoint: false,
          ),
          TextField(
            controller: _noteController,
            decoration: InputDecoration(),
          ),
          SizedBox(
            height: 8.w,
          ),
          ElevatedButton(
            onPressed: _transfer,
            child: Text("立即转赠"),
          )
        ],
      ),
    );
  }

  /// 获取参数
  void _fetchPointTransferParam() async {
    final api = context.read<NewApi>();
    try {
      final pointTransferParam = await api.pointTransferParam();
      if (!mounted) {
        return;
      }
      setState(() {
        _param = pointTransferParam;
        _accountTypeItem =
            pointTransferParam.accountTypes.firstWhere((element) => element.selected, orElse: null);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    }
  }

  /// 显示账号
  void _showAccountType() async {
    final accountTypeItem = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final data = _param.accountTypes[index];
            return ListTile(
              title: Text("${data.name}"),
              onTap: () => Navigator.of(context).pop(data),
            );
          },
          itemCount: _param.accountTypes.length,
        );
      },
    );
    if (accountTypeItem != null) {
      setState(() {
        _accountTypeItem = accountTypeItem;
      });
    }
  }

  /// 显示受赠账号
  void _showInUsername() async {
    final inUsername = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final data = _param.inUsernames[index];
            return ListTile(
              title: Text("$data"),
              onTap: () => Navigator.of(context).pop(data),
            );
          },
          itemCount: _param.inUsernames.length,
        );
      },
    );
    if (inUsername != null) {
      setState(() {
        _inUsername = inUsername;
      });
    }
  }

  /// 提交数据
  void _transfer() async {
    final req = PointTransferReq(
      accountType: _accountTypeItem?.accountType,
      amount: double.tryParse(_amountController.text),
      note: _noteController.text,
      password: _passwordController.text,
      username: _inUsername,
    );
    final api = context.read<NewApi>();
    EasyLoading.show();
    try {
      await api.pointTransfer(req);
      EasyLoading.showToast("转赠成功");
      // 清除条件
      _clearParam();
      // 自动调转到转赠历史
      Navigator.of(context).pushNamed(
        PointTransferHistoryScreen.routeName,
        arguments: PointTransferQueryReq(
          pageIndex: 0,
          pageSize: 10,
        ),
      );
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 清除条件
  void _clearParam() {
    setState(() {
      _accountTypeItem = null;
      _inUsername = null;
    });
    _amountController.clear();
    _passwordController.clear();
    _noteController.clear();
  }
}

class ParamsTextWidget extends StatelessWidget {
  final String text;
  final bool showPoint;

  const ParamsTextWidget({
    Key key,
    this.text,
    this.showPoint = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        if (showPoint)
          Text(
            "*",
            style: TextStyle(color: Colors.red),
          ),
        Text(text)
      ],
    );
  }
}
